<?php
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\WxCompany as admin;
use app\madmin\model\WxCustomer;
use think\db\exception\PDOException;

class WxCompanyService
{
    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {
        $list = admin::where($data)
                ->paginate(['page' => $page, 'list_rows' => $size])
                ->toArray();
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 保存数据
     * @param array $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(array $data)
    {
        $model = admin::create($data);
        return [HTTP_CREATED, ["model" => $model]];
    }


    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = admin::find($id);
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 获取该企业的客服
     * @param int $id
     * @return array
     */
    public function getCS(int $id)
    {
        $customer = admin::find($id)->customer;
        return [HTTP_SUCCESS, $customer];
    }

    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     */
    public function update(int $id, array $data)
    {
        try {
            $data['update_time'] = date("Y-m-d H:i:s", time());
            $admin = admin::update($data, ['id' => $id]);
        } catch (PDOException $e) {
            throw new \PDOException('发生错误！', HTTP_INVALID);
        }
        return [HTTP_CREATED, $admin];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        admin::destroy($id);
        WxCustomer::where('company_id', $id)->delete();
        return HTTP_NOCONTEND;
    }

}
